Python __init__()

Constructors are used to initializing the object’s state. The task of constructors is to initialize(assign values) to the data members of the class when an object of the class is created. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. It is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your

# A Sample class with init method
class Person:

# init method or constructor
def __init__(self, name):
self.name = name

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Nikhil')
p.say_hi()


# A Sample class with init method
class Person:
# init method or constructor
def __init__(self,name):
self.name = name

# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)

# Creating different objects
p1 = Person('Nikhil')
p2 = Person('Abhinav')
p3 = Person('Anshul')

p1.say_hi()
p2.say_hi()
p3.say_hi()

When you create a new object of a class, Python automatically calls the __init__() method to initialize the object’s attributes. Unlike regular methods, the __init__() method has two underscores (__) on each side. Therefore, the __init__() is often called dunder init. The name comes abbreviation of the double underscores init. The double underscores at both sides of the __init__() method indicate that Python will use the method internally. In other words, you should not explicitly call this method. Since Python will automatically call the __init__() method immediately after creating a new object, you can use the __init__() method to initialize the object’s attributes.

The following defines the Person class with the __init__() method:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
if __name__ == '__main__':
person = Person('John', 25)
print(f"I'm {person.name}. I'm {person.age} years old.")


# Write Python3 code here
class car():

# init method or constructor
def __init__(self, model, color):
self.model = model
self.color = color

def show(self):
print("Model is", self.model)
print("color is", self.color)

# both objects have different self which
# contain their attributes
audi = car("audi a4", "blue")
ferrari = car("ferrari 488", "green")

audi.show() # same output as car.show(audi)
ferrari.show() # same output as car.show(ferrari)

# note:we can also do like this
print("Model for audi is ", audi.model)
print("Colour for ferrari is ", ferrari.color)


When you create an instance of the Person class, Python performs two things:

  • First, create a new instance of the Person class by setting the object’s namespace such as __dict__ attribute to empty ({}).
  • Second, call the __init__ method to initialize the attributes of the newly created object.

Note that the __init__ method doesn’t create the object but only initializes the object’s attributes. Hence, the __init__() is not a constructor. If the __init__ has parameters other than the self, you need to pass the corresponding arguments when creating a new object like the example above. Otherwise, you’ll get an error.

The _init_ method with default parameter.

class Person:
def __init__(self, name, age=22):
self.name = name
self.age = age
if __name__ == '__main__':
person = Person('John')
print(f"I'm {person.name}. I'm {person.age} years old.")


No comments:

Post a Comment